package main

import (
	"fmt"
	"flag"
	"os"
	"time"
	"log"
	"github.com/hoisie/web.go"
)

var (
	host            *string = flag.String("host", "0.0.0.0", "web server bind host/address")
	port            *int    = flag.Int("port", 7001, "web server bind port")
	max_age_seconds int64   = (60 * 60)
	cache           map[string]CachedWeather
)

type CachedWeather struct {
	TheWeather  *WUWeather
	LastUpdated time.Time
}

func init() {
	cache = make(map[string]CachedWeather)
}

func GetCachedWeather(location string) (*WUWeather, os.Error) {
	if cached, ok := cache[location]; ok {
		log.Printf("found cached Weather for %s", location)
		if (time.UTC().Seconds() - cached.LastUpdated.Seconds()) <= max_age_seconds {
			log.Printf("using cached Weather for %s\n", location)
			return cached.TheWeather, nil
		}
	}
	w, err := GetWeather(location)
	if err != nil {
		return w, err
	}
	cache[location] = CachedWeather{w, *time.UTC()}
	log.Printf("cached Weather for %s\n", location)
	return w, nil
}

func main() {
	flag.Parse()
	web.Get("/", get_root)
	web.Get("/css/(.*)", get_css)
	web.Get("/favicon.ico", get_favicon)
	web.Get("/(.*)", get_path)
	web.Run(fmt.Sprintf("%s:%d", *host, *port))
}
